package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_gender

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.interstitial.api.ATInterstitial
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativePrepareExInfo
import com.anythink.nativead.api.ATNativePrepareInfo
import com.bp.hearthealth.pulse.lnapps.BuildConfig
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.model.PreloadAds
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.SelfRenderViewUtil
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.SplashType
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObservable
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObserver
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityGenderBgBinding
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.BpTimerPickerDialog
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DateUtils
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.hjq.toast.Toaster
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Timer
import java.util.TimerTask

class BpGenderActivity : BpBaseActivity<ActivityGenderBgBinding>(), TopOnSplashFinishObserver {

    private var nativeAd: NativeAd? = null
    private var adInterLaunchGender: Boolean = true
    private val viewModel: BpGenderViewModel by viewModel()
    private var topOnNativeAd: com.anythink.nativead.api.NativeAd? = null

    override fun initData() {
        super.initData()
        //性别选择页-页面展示
        AppsFlyerUtils.trackEvent("gender_show")
        registerObserver()
        binding.viewModel = viewModel
        viewModel.initDate()
        if (AdsSwitch.getBoolean(AdsSwitch.adNativeGender)) {
//            loadNativeAd()
            loadTopOnNativeAd()
        }
        adInterLaunchGender = AdsSwitch.getBoolean(AdsSwitch.adInterLaunchGender)
        if (!AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl) && adInterLaunchGender) {
            TopOnInterAdManager.manualLoadAd()
        }
        TopOnSplashFinishObservable.registerSplash(this)
//        PreloadAds.loadAds(true)
    }


    override fun onPause() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onPause()
        }
        super.onPause()
    }

    override fun onResume() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onResume()
        }
        super.onResume()
    }



    private fun loadTopOnNativeAd() {
        if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
            setNativeTopOnAdView()
        } else {
            TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener{
                override fun onNativeAdLoaded() {
                    LogUtil.iTopOn("TopOn 【原生广告】 监听，显示广告")
                    if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
                        setNativeTopOnAdView()
                    }
                }
            })
        }
    }

    private fun setNativeTopOnAdView() {
        topOnNativeAd = TopOnNativeAdManager.getNativeAds().first()
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdImpressed(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.removeUsedNativeAdListener()
            }
        })
        binding.nativeAdView.removeAllViews()
        var mNativePrepareInfo: ATNativePrepareInfo? = null
        try {
            mNativePrepareInfo = ATNativePrepareExInfo()
            if (topOnNativeAd?.isNativeExpress == true) {
                LogUtil.iTopOn("【原生广告】 自渲染广告")
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    null
                )
            } else {
                LogUtil.iTopOn("【原生广告】 模板广告")
                SelfRenderViewUtil.bindSelfRenderView(
                    activity,
                    topOnNativeAd?.adMaterial,
                    binding.nativeSelfrenderView.root,
                    mNativePrepareInfo
                )
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    binding.nativeSelfrenderView.root
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        topOnNativeAd?.prepare(binding.nativeAdView, mNativePrepareInfo)
        binding.nativeAdView.visibility = View.VISIBLE
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdCloseButtonClick(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.destroyAd()
                binding.nativeAdView.visibility = View.GONE
            }
        })
    }





    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_gender_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f6647205653da6")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【性别选择页_原生广告】")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    /**
     * 展示广告
     *     ■ 插页广告资源加载到，立即展示，广告关闭后自动跳转至主页
     *     ■ 插页广告资源未加载到，自动跳转至主页
     */
    private fun loadAdMobInsertAd() {
        if (adInterLaunchGender) {
            AdMobInterstitialAdManager.setInterstitialAdListener(object :
                AdMobInterstitialAdListener {
                override fun onAdDismissedFullScreenContent() {
                    startBpMainActivity()
                }

                override fun onNotReady() {
                    startBpMainActivity()
                }

                override fun onAdFailedToShowFullScreenContent() {
                    startBpMainActivity()
                }

                override fun onAdShowedFullScreenContent() {
                    //第一次启动-插页广告展示   ad_inter_first_open_show
                    AppsFlyerUtils.trackEvent("ad_inter_first_open_show")
                }
            })
            AdMobInterstitialAdManager.showInterstitialAd(this)
        } else {
            startBpMainActivity()
        }
    }

    private fun loadTopOnInsertAd() {
        TopOnNativeAdManager.removeUsedNativeAdListener()
        topOnNativeAd?.let { TopOnNativeAdManager.removeUsedNativeAd(it) }
//        if (BuildConfig.DEBUG) {
//            adInterLaunchGender = true
//        }
        if (adInterLaunchGender) {
            if (TopOnInterAdManager.isAdReady()) {
                TopOnInterAdManager.setManualLoadListener(object : TopOnInterstitialAdListener{
                    override fun onFireBaseAdIsClosed() {
                        startBpMainActivity()
                    }

                    override fun onInterstitialAdClose(entity: ATAdInfo) {
                        startBpMainActivity()
                    }

                    override fun onInterstitialAdShow(entity: ATAdInfo) {
                        ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471ecdee8f4")
                        LogUtil.iTopOn("TopOn 配置的场景ID为: 【第一次启动_性别选择页后_插页广告】")
                    }
                })
                TopOnInterAdManager.showInterstitialAd(this)
            } else {
                startBpMainActivity()
            }
        } else {
            startBpMainActivity()
        }
    }

    private fun startBpMainActivity() {
        TopOnInterAdManager.setManualLoadListener(null)
        TopOnSplashFinishObservable.notifySplash(SplashType.TYPE_LAUNCH_FINISH)
        startActivity(Intent(this@BpGenderActivity, BpMainActivity::class.java))
        finish()
    }

    override fun initListener() {
        super.initListener()
        binding.tvContinue.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                viewModel.save(Constants.USER_ID)
            }
        })
        binding.tvSkip.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                //需记录是否再次展示性别页面
                viewModel.updateIsFirstOpen()
            }
        })
        binding.ivBirthdayChange.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                showTimerPicker()
            }
        })
    }

    private fun showTimerPicker() {
        BpTimerPickerDialog(activity!!,
            Constants.TYPE_DATE,
            "Date",
            Constants.monthList,
            object : BpTimerPickerDialog.TimePickerCallback {
                override fun setDate(
                    year: String,
                    month: String,
                    day: String,
                    hour: String,
                    minute: String,
                    type: String
                ) {
                    // 确定按钮的回调
                    if (type == Constants.TYPE_DATE) {
                        viewModel.birthdayBean.value =
                            BpGenderViewModel.BirthdayRequestParam(year, month, day)
                        viewModel.showBirthday.set("${year}.${Constants.monthList[month.toInt() - 1]} $day")
                        viewModel.saveTimeStr = "${year}${month}${day}"
                        LogUtil.i("需要保存的日期为：${viewModel.saveTimeStr}")
                        LogUtil.i("需要保存的日期为：${DateUtils.stringToDateStamp(viewModel.saveTimeStr)}")
                    } else {
                        viewModel.saveTimeStr = "${hour}:${minute}"
                        LogUtil.i(
                            "需要保存的时间为：${
                                DateUtils.getCurrentDateTimestamp() + DateUtils.stringToTimeStamp(
                                    viewModel.saveTimeStr
                                )
                            }"
                        )
                    }
                }
            }).show()
    }


    private fun registerObserver() {
        viewModel.updateBirthdayAndGender.observe(this, Observer { result ->
            val code = result.getOrNull()
            if (code == null) {
                Toaster.show(result.exceptionOrNull())
                result.exceptionOrNull()?.printStackTrace()
                return@Observer
            }
            if (code > 0) {
                LogUtil.i("生日、性别保存成功")
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        })
        viewModel.firstOpen.observe(this) { firstOpen ->
            if (firstOpen > 0) {
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        }
        viewModel.genderId.observe(this) { genderId ->
            if (genderId == 0) {
                binding.ivGirlBg.setImageResource(R.mipmap.gender_girl_normal_bg_bp)
                binding.ivBoyBg.setImageResource(R.mipmap.gender_boy_bg_bp)
            } else {
                binding.ivBoyBg.setImageResource(R.mipmap.gender_boy_normal_bg_bp)
                binding.ivGirlBg.setImageResource(R.mipmap.gender_girl_bg_bp)
            }
        }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun onDestroy() {
        super.onDestroy()
        TopOnSplashFinishObservable.unRegisterSplash(this)
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }

    override fun topOnSplashFinish(splashType: SplashType) {
        if (splashType == SplashType.TYPE_LAUNCH_FINISH) {
            LogUtil.iTopOn("销毁性别界面")
            finish()
        }
    }
}